//
//  JLocationInfo.m
//  jhf
//
//  Created by 计海峰 on 16/11/23.
//  Copyright © 2016年 计海峰. All rights reserved.
//

#import "JLocationInfo.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapView.h>

@interface JLocationInfo ()

@property (nonatomic, strong) AMapLocationManager *manager;

@end

@implementation JLocationInfo

+ (void)load {
    [super load];
    JLocationInfo *tempRego = [[JLocationInfo alloc] init];
    tempRego.showName = @"安徽省人民政府";
    tempRego.city = @"合肥市";
    tempRego.province = @"安徽省";
    tempRego.district = @"滨湖新区";
    tempRego.formattedAddress = @"合肥市滨湖新区中山路1号";
    tempRego.longitude = 117.336623;
    tempRego.latitude = 31.74058;
    tempRego.adcode = @"340103";
    [tempRego updateLocationInfo:J_DEFAULT_INFO];
}

JSingletonM();


//MARK: - 配置
- (void)configKey:(NSString *)key lbsResult:(BlockBool)block {
    [[AMapServices sharedServices] setEnableHTTPS:YES];
    
    [AMapLocationManager updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [AMapLocationManager updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];

    [AMapSearchAPI updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [AMapSearchAPI updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];

    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
        
    [AMapServices sharedServices].apiKey = key;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self startLocationWithResult:block];
    });
}

//MARK: -  开始定位
- (void)startLocationWithResult:(void (^)(BOOL result))result {
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信 息。
    @weakify(self);
    [self.manager requestLocationWithReGeocode:true completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        //存储位置信息
        if (error) {
            if (result) {
                result(NO);
            }
            
            if (error.code == AMapLocationErrorLocateFailed) {  // 定位位错误
                NSLog(@"定位失败，可能是权限问题");
                static dispatch_once_t onceToken;
                dispatch_once(&onceToken, ^{
                    @strongify(self);
                    if ([JLocationInfo checkLocationAuthority]) {
                        [self startLocationWithResult:^(BOOL result) { }];
                    };
                });
                return ;
            }
            
            if (error.code == AMapLocationErrorCanceled)     //定位取消
            {
                NSLog(@"定位取消,locationManager可能被释放了");
                return ;
            }
            
            if (error.code == AMapLocationErrorTimeOut) //定位超时
            {
                NSLog(@"定位超时");
                return ;
            }
        }
        
        // 未报错情况  未获取到地址信息
        if (!regeocode) {   //未知情况下的定位失败
            NSLog(@"未知情况下的定位失败");
            if (result) {
                result(NO);
            }
            return;
        }
        
        // 正常获取数据成功 更定本地数据
        JLocationInfo *locationInfo = [JLocationInfo mj_objectWithKeyValues:regeocode];
        locationInfo.latitude = location.coordinate.latitude;
        locationInfo.longitude = location.coordinate.longitude;
        if (locationInfo.adcode.length > 2) {
            locationInfo.adcode = [locationInfo.adcode substringToIndex:locationInfo.adcode.length - 2];
            locationInfo.adcode = [NSString stringWithFormat:@"%@00", locationInfo.adcode];
        }
        [locationInfo updateLocationInfo:J_LBS_INFO];
        if (result) {
            result(YES);
        }
    }];
    
}

//MARK: -  优先级返回
+ (JLocationInfo *)showDefaultInfo {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    JLOCATIONINFO type = J_DEFAULT_INFO;
    if ([userDefault objectForKey:J_SELECT_LOCATION_INFO_KEY]) {
        type = J_CHOOSE_INFO;
    }else if([userDefault objectForKey:J_LBS_LOCATION_INFO_KEY]) {
        type = J_LBS_INFO;
    }
    return [[self class] showLocationInfo:type];
}

/**
 设置默认位置 合肥
 */
 + (void)configDefaultLocation:(JLocationInfo *)info {
     [info updateLocationInfo:J_DEFAULT_INFO];
}

//MARK: -  显示位置
+ (JLocationInfo *)showLocationInfo:(JLOCATIONINFO)type {
    JLocationInfo *lcoationInfo;
    NSString *key = J_DEFAULT_DEFAULT_INFO_KEY;
    switch (type) {
        case J_LBS_INFO:
            key = J_LBS_LOCATION_INFO_KEY;
            break;
        case J_CHOOSE_INFO:
            key = J_SELECT_LOCATION_INFO_KEY;
            break;
        default:
            break;
    }
    lcoationInfo = [JLocationInfo mj_objectWithKeyValues:[[NSUserDefaults standardUserDefaults] objectForKey:key]];
    return lcoationInfo;
}

//MARK: -   更新位置
- (void)updateLocationInfo:(JLOCATIONINFO)type {
    NSString *key = J_DEFAULT_DEFAULT_INFO_KEY;
    switch (type) {
        case J_LBS_INFO:
            key = J_LBS_LOCATION_INFO_KEY;
            break;
        case J_CHOOSE_INFO:
            key = J_SELECT_LOCATION_INFO_KEY;
            break;
        default:
            break;
    }
    NSLog(@"%@", self.mj_JSONString);
    if (self.adcode.length > 2 && ![self.adcode hasSuffix:@"00"]) {
        self.adcode = [self.adcode substringToIndex:self.adcode.length - 2];
        self.adcode = [NSString stringWithFormat:@"%@00", self.adcode];
    }
    [[NSUserDefaults standardUserDefaults] setValue:self.mj_JSONString forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:key object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCATION_INFO_CHANGE_KEY object:nil];
}

/**
 删除某种位置信息
 
 @param type 位置类型
 */
+ (void)removeLocationInfo:(JLOCATIONINFO)type {
    NSString *key = J_DEFAULT_DEFAULT_INFO_KEY;
    switch (type) {
        case J_LBS_INFO:
            key = J_LBS_LOCATION_INFO_KEY;
            break;
        case J_CHOOSE_INFO:
            key = J_SELECT_LOCATION_INFO_KEY;
            break;
        default:
            break;
    }
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:key object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:J_LOCATION_INFO_CHANGE_KEY object:nil];
}


//MARK: -  检查位置权限
+ (BOOL)checkLocationAuthority {
    BOOL result = true;
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) { //
        result = true;
    }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){ // 拒绝
        result = false;
    }
    return result;
}


//MARK: -
- (CGFloat)longitude {
    return  fabs(_longitude);
}


- (CGFloat)latitude {
    return fabs(_latitude);
}

//MARK: - lazy
- (AMapLocationManager *)manager {
    if (!_manager) {
        AMapLocationManager *manager = [[AMapLocationManager alloc] init];
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [manager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        //   定位超时时间，最低2s，此处设置为10s
        manager.locationTimeout = 20;
        //   逆地理请求超时时间，最低2s，此处设置为10s
        manager.reGeocodeTimeout = 20;
        _manager = manager;
    }
    return _manager;
}

+ (NSArray *)mj_ignoredPropertyNames {
    return @[@"manager"];
}

@end
